package com.example.administrator.hqq.activity.mine;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.example.administrator.hqq.R;
import com.example.administrator.hqq.View.alertview.AlertViewFactory;
import com.example.administrator.hqq.View.layout.EmptyLayout;
import com.example.administrator.hqq.activity.drag.PhotoActivity;
import com.example.administrator.hqq.activity.post.PostDetailsActivity;
import com.example.administrator.hqq.adapter.discover.PostListAdapter;
import com.example.administrator.hqq.base.MyActivity;
import com.example.administrator.hqq.bean.post.PostModuleBean;
import com.example.administrator.hqq.config.LoongsConfig;
import com.example.administrator.hqq.config.UrlFactory;
import com.example.administrator.hqq.utils.GetLocationUtils;
import com.example.administrator.hqq.utils.HintWordsUtils;
import com.google.gson.Gson;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhy.autolayout.AutoRelativeLayout;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class MyFavoriteActivity extends MyActivity {

    @BindView(R.id.return_auto)
    AutoRelativeLayout returnAuto;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.report_auto)
    AutoRelativeLayout reportAuto;
    @BindView(R.id.group_lv)
    ListView groupLv;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.empty)
    EmptyLayout empty;
    private List<PostModuleBean.DataBean> listViewData;//数据源
    private PostListAdapter postListAdapter;
    private int page = 1;
    private int position = 0;
    private String TAG = this.getClass().getSimpleName();
    private ArrayList<String> strings;
    private String last_id = "";
    private AlertDialog showReportAlertView;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_favorite);
        ButterKnife.bind(this);
        initview();
        initdata();
        initOnclick();
    }

    private void initdata() {
        empty.hide();
        if (page == 1 || listViewData.size() <= 0) {
            last_id = "";
        } else {
            last_id = listViewData.get(listViewData.size() - 1).getId();
        }
        OkHttpUtils.get().url(UrlFactory.getCollectionForum()).tag(this)
                .addParams(LoongsConfig.user_id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                .addParams(LoongsConfig.city_code, GetLocationUtils.getCityCode())
                .addParams(LoongsConfig.last_id, last_id)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "onError: " + e.getMessage());
                if (empty!=null)
                empty.showEmpty();
                if (refreshLayout != null) {
                    refreshLayout.finishRefresh();
                    refreshLayout.finishLoadMore();
                }
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "onResponse: " + response);
                if (refreshLayout != null) {
                    refreshLayout.finishRefresh();
                    refreshLayout.finishLoadMore();
                }
                Gson gson = new Gson();
                PostModuleBean postModuleBean = gson.fromJson(response, PostModuleBean.class);
                if (postModuleBean.getCode() == 200) {
                    if (page == 1) {
                        if (postModuleBean.getData()==null||postModuleBean.getData().size()==0){
                            empty.showEmpty();
                        }
                        listViewData.clear();
                    }
                    listViewData.addAll(postModuleBean.getData());
                    postListAdapter.notifyDataSetChanged();
                }
            }
        });
    }

    private void initview() {
        strings=new ArrayList<>();
        View inflate = getLayoutInflater().inflate(R.layout.forum_head_view_layout, null);
        title.setText("我的收藏");
        listViewData = new ArrayList<>();
        postListAdapter = new PostListAdapter(this, listViewData);
        groupLv.setAdapter(postListAdapter);
        groupLv.addHeaderView(inflate);
        //设置刷新动画
        refreshLayout.setEnableAutoLoadMore(false);
        refreshLayout.setRefreshHeader(new MaterialHeader(this));
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                //下拉刷新
                page = 1;
                initdata();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                //上拉加载
                page++;
                initdata();
            }
        });
    }

    private void initOnclick() {
        postListAdapter.setOnClick(new PostListAdapter.OnClick() {
            @Override
            public void lookPic(int i, int i1) {
//                Intent intent = new Intent(getContext(), PhotoActivity.class);
//                intent.putExtra(LoongsConfig.url,listViewData.get(i).getPicture_url().get(i1).getOrigin());
//                startActivity(intent);
                ArrayList<String> strings = new ArrayList<>();
                for (int i2 = 0; i2 < listViewData.get(i).getPicture_url().size(); i2++) {
                    strings.add(listViewData.get(i).getPicture_url().get(i2).getOrigin());
                }
                PhotoActivity.start(MyFavoriteActivity.this, strings, i1);
            }

            @Override
            public void giveLike(final int i, final ImageView image, TextView textView) {
                listViewData.get(i).setLike_amount(image.isSelected() ? listViewData.get(i).getLike_amount() - 1 : listViewData.get(i).getLike_amount() + 1);
                listViewData.get(i).setLike_state(image.isSelected() ? 0 : 1);
                postListAdapter.notifyDataSetChanged();
                OkHttpUtils.get().url(UrlFactory.getForumlike())
                        .addParams(LoongsConfig.user_id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                        .addParams(LoongsConfig.forum_id, listViewData.get(i).getId())
                        .addParams(LoongsConfig.value, image.isSelected() ? "0" : "1")
                        .build().execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e(TAG, "点赞onError: " + e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e(TAG, "点赞onResponse: " + response);
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (jsonObject.getInt(LoongsConfig.code) == 200) {
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });
            }

            @Override
            public void details(int i) {
                position = i;
                Log.e("kang", "details: ");
                Intent intent = new Intent(MyFavoriteActivity.this, PostDetailsActivity.class);
                intent.putExtra(LoongsConfig.forum_id, listViewData.get(i).getId());
                intent.putExtra(LoongsConfig.name,listViewData.get(i).getTopic_name());
                startActivity(intent);
            }

            @Override
            public void report(final int i) {
                if ("MINE".equals(listViewData.get(i).getType())){
                    AlertDialog.Builder normalDialog = new AlertDialog.Builder(MyFavoriteActivity.this);
                    normalDialog.setTitle("确定要删除此帖子吗");
                    normalDialog.setPositiveButton("确定",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    deleteForum(i);
                                }
                            });
                    normalDialog.setNegativeButton("关闭",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    //...To-do
                                }
                            });
                    // 显示
                    normalDialog.show();
                }else{
                    reportForum(i);
                }

            }
            @Override
            public void joinGroup(int Position){
//                joinGroupCheck(position);
            }
        });
    }

    /**
     * 举报帖子内容
     * @param i
     */
    private void reportForum(final int i) {
        strings.clear();
        for (String s : this.getResources().getStringArray(R.array.forum_report)) {
            strings.add(s);
        }
        showReportAlertView = AlertViewFactory.getInstance().getShowReportAlertView(this, strings, new AlertViewFactory.ReportOnClickListener() {
            @Override
            public void submit(int position) {
                Log.e(TAG, "submit: " + position);
                showReportAlertView.cancel();
                OkHttpUtils.get().url(UrlFactory.ReportForum())
                        .addParams(LoongsConfig.id, listViewData.get(i).getId())
                        .addParams(LoongsConfig.type, "0")
                        .addParams(LoongsConfig.user_id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                        .addParams(LoongsConfig.reason_id, position + 101 + "")
                        .build().execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e(TAG, "举报onError: " + e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e(TAG, "举报response: " + response);
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            int code = jsonObject.getInt(LoongsConfig.code);
                            HintWordsUtils.showMarkeWords(jsonObject.getInt(LoongsConfig.code), jsonObject.getString(LoongsConfig.description));
                            if (code == 200) {
                                ToastUtils.showShort("已提交举报");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
                listViewData.remove(i);
                postListAdapter.notifyDataSetChanged();
            }
        });
    }

    /**
     * 删除自己的帖子
     * @param i
     */
    private void deleteForum(final int i) {
        OkHttpUtils.get().url(UrlFactory.deleterMyforum()).tag(this)
                .addParams(LoongsConfig.user_id,LoongsConfig.getUser_id())
                .addParams(LoongsConfig.forum_id,listViewData.get(i).getId())
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "贴子删除onError: "+e.getMessage() );
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "贴子删除onResponse: "+response );
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    int code = jsonObject.getInt(LoongsConfig.code);
                    String description = jsonObject.getString(LoongsConfig.description);
                    if (code==200){
                        listViewData.remove(i);
                        postListAdapter.notifyDataSetChanged();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @OnClick(R.id.return_auto)
    public void onViewClicked() {
        finish();
    }

    @Override
    protected String getActivityName() {
        return this.getClass().getSimpleName();
    }
}
